package cn.yitun.chat.yitunservermanagecore.general.manage.core.manager;

import cn.yitun.chat.yitunservercommonlib.dataentity.dto.userchat.SecurityQuestionDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.userchat.SecurityQuestionVo;
import cn.yitun.chat.yitunservercommonlib.util.R;
import cn.yitun.chat.yitunserverimbase.dao.userchat.SecurityQuestionDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SecurityQuestionManager {

	@Resource
	private SecurityQuestionDao securityQuestionDAO;

	/**
	 * 
	 * Date 2019-01-20 09:14:05<br>
	 * Description 保存密保问题
	 * 
	 * @author yitun<br>
	 * @param list
	 * @param userId
	 * @version 1.1
	 */
	@Transactional
	public void save(List<SecurityQuestionDto> list, Long userId) {
		if (null != list) {
			for (SecurityQuestionDto sq : list) {
				sq.setUserId(userId);
				sq.setCreateBy(userId);
				sq.setUpdateBy(userId);
				securityQuestionDAO.save(sq);
			}
		}
	}

	/**
	 * 
	 * Date 2019-01-20 09:21:35<br>
	 * Description 检查密保问题是否正确
	 * 
	 * @author yitun<br>
	 * @param userId
	 * @param        answerList:回答列表
	 * @return
	 * @version 1.1
	 */
	public boolean check(Long userId, List<SecurityQuestionDto> answerList) {
		boolean check = true;
		List<SecurityQuestionVo> questionList = securityQuestionDAO.listVO(R.param("userId", userId));
		if (null != questionList && !questionList.isEmpty() && null != answerList && !answerList.isEmpty()) {
			int answerSize = answerList.size();
			int questionSize = questionList.size();
			// 如果回答数量和问题数量不一致，则回答错误
			if (answerSize == questionSize) {
				Map<Long, String> map = new HashMap<>();
				for (SecurityQuestionDto sq : answerList) {
					map.put(sq.getId(), sq.getAnswer());
				}
				for (SecurityQuestionVo sq : questionList) {
					Long id = sq.getId();
					String answer = sq.getAnswer();
					//如果其中一个回答错误，则回答错误
					if (null == answer || !answer.equals(map.get(id))) {
						check = false;
						break;
					}
				}
			} else {
				check = false;
			}

		} else {
			check = false;
		}
		return check;
	}
}
